<template>
  <el-table
    :data="pages"
    :show-header="false"
  >
    <el-table-column>
      <template slot-scope="scope">
        <span>
          <svg-icon class="icon el-select" :icon-class="componentMap[scope.row] ? componentMap[scope.row].meta.icon : ''" />
          <span>{{ componentMap[scope.row] ? componentMap[scope.row].label : scope.row }}</span>
        </span>
      </template>
    </el-table-column>
    <el-table-column width="30">
      <template slot-scope="scope">
        <el-button
          type="danger"
          circle
          style="padding:3px;"
          title="删除功能"
          size="mini"
          @click="() => handleDelete(scope.row)"
        >
          <svg-icon icon-class="delete" />
        </el-button>
      </template>
    </el-table-column>
  </el-table>
</template>

<script>
export default {
  name: 'Pages',
  props: {
    fnAdd: { type: Function, required: true },
    fnRemove: { type: Function, required: true },
    roleId: { type: String, required: true },
    componentMap: {
      type: Object,
      default() { return {} }
    },
    selected: {
      type: Array,
      default() { return [] }
    }
  },
  data() {
    return {
      pages: []
    }
  },
  methods: {
    setSelect(select) {
      this.pages = select
    },
    handleDelete(component) {
      this.fnRemove(this, { roleId: this.roleId, pages: [component] }).then(res => {
        if (res) {
          this.pages.forEach((item, index) => {
            if (item === component) {
              this.pages.splice(index, 1)
            }
          })
          this.$emit('restorePages', this.pages)
        }
      })
    },
    updateSelect(select) {
      if (select.length > this.pages.length) {
        this.addPages(select)
      } else if (select.length < this.pages.length) {
        this.removePages(select)
      }
      // console.log('updateSelect', select)
    },
    removePages(select) {
      // 删除
      const remmoves = []
      this.pages.forEach(comp => {
        let found = false
        for (let n = 0; n < select.length; n++) {
          if (select[n] === comp) {
            found = true
            break
          }
        }
        if (!found) {
          remmoves.push(comp)
        }
      })
      this.fnRemove(this, { roleId: this.roleId, pages: remmoves }).then(() => {
        this.setSelect(select)
      }).catch(() => {
        this.$emit('restorePages', this.pages)
      })
    },
    addPages(select) {
      // 增加
      const adds = []
      select.forEach(comp => {
        let found = false
        for (let n = 0; n < this.pages.length; n++) {
          if (this.pages[n] === comp) {
            found = true
            break
          }
        }
        if (!found) {
          adds.push(comp)
        }
      })
      this.fnAdd(this, { roleId: this.roleId, pages: adds }).then(() => {
        this.setSelect(select)
      }).catch(() => {
        this.$emit('restorePages', this.pages)
      })
    }
  }
}
</script>
